import json
import math
import bisect
from pathlib import Path

PATH = Path(__file__).resolve().parent

class Chi2_Table_Checker:
    def __init__(self):
        with open(PATH.joinpath('chi2_p_table.json'), 'r') as f:
            table = json.load(f)
        self.X = sorted(table['X'])
        self.Y = table['Y']

    def get_p(self, x: float) -> float:
        if x < self.X[0]:
            return 1.0
        elif x > self.X[-1]:
            return 0.0
        else:
            index_X = bisect.bisect_right(self.X, x)
            index_Y = len(self.X) - index_X - 1
            if index_X == len(self.X):
                return self.Y[0]
            elif index_X == 0:
                return self.Y[-1]
            else:
                x0 = self.X[index_X - 1]
                x1 = self.X[index_X]
                y0 = self.Y[index_Y]
                y1 = self.Y[index_Y + 1]
                return y0 - (y0 - y1) / (x1 - x0) * (x - x0)